Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [1]:
# Load pickled data
import pickle

# TODO: Fill this in based on where you saved the training and testing data

training_file = 'pickle/train.p'
validation_file='pickle/valid.p'
testing_file = 'pickle/test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [2]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results

import pandas as pd
import numpy as np

n_train = len(X_train)
n_test = len(X_test)
n_valid = len(X_valid)
image_shape = X_train.shape

# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(pd.unique(y_train))

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Number of validation examples =", n_valid)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of testing examples = 12630
Number of validation examples = 4410
Image data shape = (34799, 32, 32, 3)
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.

In [3]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
import seaborn as sns
# Visualizations will be shown in the notebook.
%matplotlib inline

set_name = ['Training', 'Validation', 'Testing']
ysets = (y_train, y_valid, y_test)
plt.figure(figsize=(18, 8))
for i in range(3):
    plt.subplot(1, 3, i+1)
    plt.title('Label Distribution In %s Set' % (set_name[i], ))
    plt.xlim((0, 42))
    sns.distplot(ysets[i])

plt.figure(figsize=(18, 18))
for i in range(36):
    ax = plt.subplot(6, 6, i+1)
    index = i * 4
    plt.title('Traffic Signs: %s' % (y_train[index], ))
    v = X_train[index]
    ax.axis('off')
    plt.imshow(v)
/opt/anaconda3/lib/python3.5/site-packages/statsmodels/nonparametric/kdetools.py:20: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
  y = X[:m/2+1] + np.r_[0,X[m/2+1:],0]*1j

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Pre-process the Data Set (normalization, grayscale, etc.)

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [5]:
### Preprocess the data here. Preprocessing steps could include normalization, converting to grayscale, etc.
### Feel free to use as many code cells as needed.
import cv2
import random
from sklearn.preprocessing import OneHotEncoder
from sklearn.cross_validation import train_test_split

mean_image = (X_train.mean(0)).astype(np.uint8)
one_hot = OneHotEncoder()
one_hot.fit([[i] for i in range(43)])
fig, ax = plt.subplots()
ax.axis('off')
plt.title("mean image")
plt.imshow(mean_image)

class BatchGenerator(object):
    def __init__(self, X, y, batch_size=30, argue=True, shuffle=True):
        assert len(X) == len(y), "[ERROR] Input X y must have the same length!"
        assert len(X) != 0
        y = one_hot.transform([[t] for t in y])
        X = self.pre_sub_mean(X)
        if shuffle:
            X, _, y, _ = train_test_split(X, y, test_size=0.0)
        self.X = X
        self.y = y.toarray()
        self.begin = 0
        self.batch = batch_size
        self.epochs = 0
        self.argue = argue
        self.arguments = (self._random_translation, 
                          self._random_zoom)
                          #self._random_rotate)
    
    def _gen(self):
        start, end = self.begin, min(self.batch + self.begin, len(self.X))
        if end >= len(self.X):
            self.begin = 0
            self.epochs += 1
        else:
            self.begin = end
        return self.X[start:end], self.y[start:end]
    
    def get_batch(self):
        X, y = self._gen()
        if self.argue:
            argument = random.choice(self.arguments)
            X = argument(X)
        return X, y
        
    @staticmethod
    def pre_sub_mean(X):
        return X.astype(np.float32) -  mean_image

    @staticmethod
    def _random_translation(X):
        """return a set of new X, which is random translated image of X"""
        new_X = np.zeros_like(X)
        x_shift, y_shift = [random.randint(1, 12)] * 2
        xlen, ylen = X.shape[2], X.shape[1]
        new_X[:, y_shift:, x_shift:, :] = X[:, :(ylen - y_shift), :(xlen - x_shift), :]
        return new_X
        
    @staticmethod
    def _random_zoom(X):
        """return a set of new X, which is random zoomed image of X"""
        new_X = np.zeros_like(X)
        padding = random.randint(3,8)
        dsize = X.shape[1] - padding*2, X.shape[2] - padding*2
        for i in range(len(X)):
            cv2.resize(X[i], dsize, 
                       new_X[i,  padding : X.shape[1] - padding,  padding : X.shape[2] - padding, :])
        return new_X
                       
    @staticmethod
    def _random_rotate(X):
        """return a set of new X, which is random rotated image of X"""
        new_X = np.zeros_like(X)
        rotate_type = random.choice((cv2.ROTATE_90_CLOCKWISE, cv2.ROTATE_90_COUNTERCLOCKWISE))
        for i in range(len(X)):
            new_X[i] = cv2.rotate(X[i], rotate_type)
        return new_X


def test():
    batch = BatchGenerator(X_train[:9], y_train[:9])
    plt.figure(figsize=(10, 10))
    for i, argument in enumerate(([lambda x: x] + list(batch.arguments)), 1):
        ax = plt.subplot(2, 3, i)
        ax.axis('off')
        plt.imshow(argument(X_train[i:i + 1])[0])
        
test()
In [6]:
import pandas as pd

def test2(X, y):
    valid_batch = BatchGenerator(X, y, batch_size=len(X_valid), argue=False)
    df = pd.read_csv('signnames.csv')
    plt.figure(figsize=(20, 20))
    _X, _y = valid_batch.get_batch()
    for i in range(36):
        ax = plt.subplot(6, 6, 1 + i)
        plt.title(df.ix[np.argmax(_y[i])].SignName)
        ax.axis('off')
        plt.imshow(_X[i] + mean_image)
        
test2(X_test, y_test)

Model Architecture

In [7]:
import tensorflow as tf

learning_rate = tf.placeholder(tf.float32)
sigma = 0.1


def max_pool_2x2(relu):
    return tf.nn.max_pool(relu, (1,2,2,1), (1,2,2,1), padding='VALID')

def conv(X, W, b, padding='VALID'):
    _conv = tf.nn.conv2d(X, W, (1, 1, 1, 1), padding=padding)
    _conv += b
    _conv = tf.nn.relu(_conv)
    return _conv

X = tf.placeholder(tf.float32, shape=[None, 32, 32, 3])
y = tf.placeholder(tf.float32, shape=[None, 43])
dropout = tf.placeholder(tf.float32)

W = {
    'conv11': tf.Variable(tf.random_normal([3, 3, 3, 8], stddev=sigma, dtype=tf.float32), dtype=tf.float32),
    'conv12': tf.Variable(tf.random_normal([3, 3, 8, 8], stddev=sigma, dtype=tf.float32), dtype=tf.float32),
    'conv13': tf.Variable(tf.random_normal([3, 3, 8, 8], stddev=sigma, dtype=tf.float32), dtype=tf.float32),
    
    'conv21': tf.Variable(tf.random_normal([3, 3, 8, 32], stddev=sigma, dtype=tf.float32), dtype=tf.float32),
    'conv22': tf.Variable(tf.random_normal([3, 3, 32, 32], stddev=sigma, dtype=tf.float32), dtype=tf.float32),
    'conv23': tf.Variable(tf.random_normal([3, 3, 32, 32], stddev=sigma, dtype=tf.float32), dtype=tf.float32),
    
    'conv31': tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=sigma, dtype=tf.float32), dtype=tf.float32),
    'conv32': tf.Variable(tf.random_normal([3, 3, 64, 64], stddev=sigma, dtype=tf.float32), dtype=tf.float32),
    'conv33': tf.Variable(tf.random_normal([3, 3, 64, 64], stddev=sigma, dtype=tf.float32), dtype=tf.float32),
    
    'fc0': tf.Variable(tf.random_normal([1024, 128], stddev=sigma, dtype=tf.float32), dtype=tf.float32),
    'fc1': tf.Variable(tf.random_normal([128, 64], stddev=sigma, dtype=tf.float32), dtype=tf.float32),
    'fc2': tf.Variable(tf.random_normal([64, 43], stddev=sigma, dtype=tf.float32), dtype=tf.float32)
}
b = {
    'conv11': tf.Variable(tf.zeros([8], dtype=tf.float32)),
    'conv12': tf.Variable(tf.zeros([8], dtype=tf.float32)),
    'conv13': tf.Variable(tf.zeros([8], dtype=tf.float32)),
    'conv21': tf.Variable(tf.zeros([32], dtype=tf.float32)),
    'conv22': tf.Variable(tf.zeros([32], dtype=tf.float32)),
    'conv23': tf.Variable(tf.zeros([32], dtype=tf.float32)),
    
    'conv31': tf.Variable(tf.zeros([64], dtype=tf.float32)),
    'conv32': tf.Variable(tf.zeros([64], dtype=tf.float32)),
    'conv33': tf.Variable(tf.zeros([64], dtype=tf.float32)),
    'fc0': tf.Variable(tf.zeros([128], dtype=tf.float32)),
    'fc1': tf.Variable(tf.zeros([64], dtype=tf.float32)),
    'fc2': tf.Variable(tf.zeros([43], dtype=tf.float32)),
}
# 32 x 32 x 8
conv11 = conv(X, W['conv11'], b['conv11'], 'SAME')
conv12 = conv(conv11, W['conv12'], b['conv12'], 'SAME')
conv13 = conv(conv12, W['conv13'], b['conv13'], 'SAME')
# 16 x 16 x 8
conv1 = max_pool_2x2(conv13)

# 16 x 16 x 32
conv21 = conv(conv1, W['conv21'], b['conv21'], padding='SAME')
conv22 = conv(conv21, W['conv22'], b['conv22'], padding='SAME')
conv23 = conv(conv22, W['conv23'], b['conv23'], padding='SAME')
# 8, 8, 32
conv2 = max_pool_2x2(conv23)

# 8, 8, 64
conv31 = conv(conv2, W['conv31'], b['conv31'], padding='SAME')
conv32 = conv(conv31, W['conv32'], b['conv32'], padding='SAME')
conv32 = conv(conv32, W['conv33'], b['conv33'], padding='SAME')
# 4, 4, 64
conv3 = max_pool_2x2(conv32)

# 1024 -> 128
fc0 = tf.contrib.layers.flatten(conv3)
fc0 = tf.matmul(fc0, W['fc0']) + b['fc0']
fc0 = tf.nn.relu(fc0)
fc0 = tf.nn.dropout(fc0, dropout)
# 128 -> 64
fc1   = tf.matmul(fc0, W['fc1']) + b['fc1']
fc1   = tf.nn.relu(fc1)
fc1 = tf.nn.dropout(fc1, dropout)
# 64 -> 43
fc2   = tf.matmul(fc1, W['fc2']) + b['fc2']
pred  = fc2

cross_entropy = tf.nn.softmax_cross_entropy_with_logits(pred, y)
cost = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

init = tf.initialize_all_variables()
# init = tf.global_variables_initializer()

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [20]:
import os
from datetime import datetime
max_epochs = 30
log_steps = 1000
save_epochs = 10
max_epochs = 1000


train_batch = BatchGenerator(X_train, y_train, batch_size=300)
test_batch = BatchGenerator(X_test, y_test, batch_size=len(X_test), argue=False)
valid_batch = BatchGenerator(X_valid, y_valid, batch_size=len(X_valid), argue=False)


with tf.Session() as sess:
    sess.run(init)
    file_path = "model/mine_3.ckpt"
    meta_path = "model/mine_3.ckpt.meta"
    if os.path.exists(meta_path):
#         saver = tf.train.Saver(tf.global_variables())
        saver = tf.train.Saver(tf.all_variables())
        print('Restore ' + file_path)
        saver.restore(sess, file_path)
    count = 0
    last_save = 0
    n_train_acc = 0
    train_acc_sum = 0
    _lr = 0.000001
    
    last_val_acc = 0
    n_small_change = 0
    while train_batch.epochs < max_epochs:
        _X, _y = train_batch.get_batch()
        
        sess.run(optimizer, feed_dict={X:_X, y:_y, dropout:0.5, learning_rate:_lr})
        train_acc_sum += sess.run(accuracy , feed_dict={X:_X, y:_y, dropout:1})
        n_train_acc += 1
        
        if count != train_batch.epochs:
            count = train_batch.epochs
            _X, _y = valid_batch.get_batch()
            val_acc = sess.run(accuracy, feed_dict={X:_X, y:_y, dropout:1})
            print("[Epochs %d] Training Accuracy %f, Validation Accuracy %f, %s" % (train_batch.epochs, 
                                                                                    train_acc_sum / n_train_acc, val_acc, 
                                                                                    str(datetime.now())))
            train_acc_sum = n_train_acc = 0
            
        if last_save != train_batch.epochs and (train_batch.epochs + 1) % save_epochs == 0:
            last_save = train_batch.epochs
            saver = tf.train.Saver(tf.all_variables())
            saver_path = saver.save(sess, "model/mine_3.ckpt")
            print("Model save " + str(saver_path))
            if val_acc - last_val_acc < 0.02:
                n_small_change += 1
                if n_small_change >= 2:
                    _lr *= 0.9
                    print("Learning Rate Change To %f" % (_lr,))
                    n_small_change = 0
            last_val_acc = max(val_acc, last_val_acc)
Restore model/mine_3.ckpt
[Epochs 1] Training Accuracy 0.984339, Validation Accuracy 0.940363, 2017-05-17 04:05:06.118098
[Epochs 2] Training Accuracy 0.986925, Validation Accuracy 0.940817, 2017-05-17 04:05:14.629995
[Epochs 3] Training Accuracy 0.985229, Validation Accuracy 0.941043, 2017-05-17 04:05:23.113984
[Epochs 4] Training Accuracy 0.984166, Validation Accuracy 0.941043, 2017-05-17 04:05:31.614840
[Epochs 5] Training Accuracy 0.983763, Validation Accuracy 0.940817, 2017-05-17 04:05:40.126548
[Epochs 6] Training Accuracy 0.984740, Validation Accuracy 0.940817, 2017-05-17 04:05:48.630185
[Epochs 7] Training Accuracy 0.986092, Validation Accuracy 0.940590, 2017-05-17 04:05:57.135401
[Epochs 8] Training Accuracy 0.985918, Validation Accuracy 0.940817, 2017-05-17 04:06:05.644743
[Epochs 9] Training Accuracy 0.985373, Validation Accuracy 0.940590, 2017-05-17 04:06:14.139507
Model save model/mine_3.ckpt
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-20-3a6d064445cd> in <module>()
     32         _X, _y = train_batch.get_batch()
     33 
---> 34         sess.run(optimizer, feed_dict={X:_X, y:_y, dropout:0.5, learning_rate:_lr})
     35         train_acc_sum += sess.run(accuracy , feed_dict={X:_X, y:_y, dropout:1})
     36         n_train_acc += 1

/opt/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    715     try:
    716       result = self._run(None, fetches, feed_dict, options_ptr,
--> 717                          run_metadata_ptr)
    718       if run_metadata:
    719         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/opt/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    913     if final_fetches or final_targets:
    914       results = self._do_run(handle, final_targets, final_fetches,
--> 915                              feed_dict_string, options, run_metadata)
    916     else:
    917       results = []

/opt/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
    963     if handle is None:
    964       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
--> 965                            target_list, options, run_metadata)
    966     else:
    967       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/opt/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
    970   def _do_call(self, fn, *args):
    971     try:
--> 972       return fn(*args)
    973     except errors.OpError as e:
    974       message = compat.as_text(e.message)

/opt/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
    952         return tf_session.TF_Run(session, options,
    953                                  feed_dict, fetch_list, target_list,
--> 954                                  status, run_metadata)
    955 
    956     def _prun_fn(session, handle, feed_dict, fetch_list):

KeyboardInterrupt: 
In [22]:
with tf.Session() as sess:
    sess.run(init)
    file_path = "model/mine_3.ckpt"
    meta_path = "model/mine_3.ckpt.meta"
    if os.path.exists(meta_path):
        saver = tf.train.Saver(tf.all_variables())
        print('Restore ' + file_path)
        saver.restore(sess, file_path)
    _X, _y = test_batch.get_batch()
    acc = sess.run(accuracy, feed_dict={X:_X, y:_y, dropout:1})
    print("Test Accuracy:{}".format(acc))
Restore model/mine_3.ckpt
Test Accuracy:0.9300082921981812

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [23]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
from PIL import Image
path = './GermanTrafficSigns/'
imgs = []
for filename in os.listdir(path):
    img = Image.open(path + filename)
    img = img.resize((32, 32))
    img.save(path + filename)
    imgs.append(plt.imread(path+filename))
imgs = np.array(imgs)

plt.figure(figsize=(18, 8))
for i in range(5):
    plt.subplot(1, 5, i+1)
    plt.imshow(imgs[i])

Predict the Sign Type for Each Image

In [26]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
signnames = pd.read_csv('./signnames.csv')
predict_batch = BatchGenerator(imgs, [0]*len(imgs), batch_size=len(imgs), argue=False, shuffle=False)

with tf.Session() as sess:
    sess.run(init)
    file_path = "model/mine_3.ckpt"
    meta_path = "model/mine_3.ckpt.meta"
    if os.path.exists(meta_path):
        saver = tf.train.Saver(tf.all_variables())
        print('Restore ' + file_path)
        saver.restore(sess, file_path)
        
    softmax = tf.nn.softmax(pred)
    _X, _y = predict_batch.get_batch()
    _pred = sess.run(softmax, feed_dict={X:_X, dropout:1})
    pred_ans = _pred.argmax(1)

pred_ans = list(map( lambda x: signnames.ix[x, 'SignName'], pred_ans)  )
plt.figure(figsize=(18, 8))
for i in range(5):
    plt.subplot(1, 5, i+1)
    plt.title(pred_ans[i])
    plt.imshow(imgs[i])
Restore model/mine_3.ckpt

Analyze Performance

In [27]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
print("Accuracy is 100%")
Accuracy is 100%

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [28]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.
with tf.Session() as sess:
    top = sess.run(tf.nn.top_k(tf.constant(_pred), 5))

print(top.values)
[[  1.00000000e+00   1.52509790e-14   3.46497901e-22   1.13301784e-24
    3.50066887e-27]
 [  1.00000000e+00   5.56379352e-11   7.85023563e-14   9.92789636e-16
    8.31953220e-16]
 [  9.98804212e-01   1.19481760e-03   9.97179427e-07   5.15983212e-09
    2.43283465e-14]
 [  9.99620438e-01   3.79505887e-04   3.90209181e-08   1.81015416e-08
    1.64512066e-08]
 [  1.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00]]

Step 4: Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Combined Image

Your output should look something like this (above)

In [29]:
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.

# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry

def outputFeatureMap(image_input, tf_activation, sess, activation_min=-1, activation_max=-1 ,plt_num=1):
    # Here make sure to preprocess your image_input in a way your network expects
    # with size, normalization, ect if needed
    # image_input =
    # Note: x should be the same name as your network's tensorflow data placeholder variable
    # If you get an error tf_activation is not defined it maybe having trouble accessing the variable from inside a function
    activation = tf_activation.eval(session=sess,feed_dict={X : image_input})
    featuremaps = activation.shape[3]
    plt.figure(plt_num, figsize=(15,15))
    for featuremap in range(featuremaps):
        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
        plt.grid(False)
        if activation_min != -1 & activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
        elif activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
        elif activation_min !=-1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
        else:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
            

def outputFeatureMapActivation(tf_activation):
    with tf.Session() as sess:
        sess.run(init)
        file_path = "model/mine_3.ckpt"
        meta_path = "model/mine_3.ckpt.meta"
        if os.path.exists(meta_path):
            saver = tf.train.Saver(tf.all_variables())
            print('Restore ' + file_path)
            saver.restore(sess, file_path)
        _X, _y = predict_batch.get_batch()
        outputFeatureMap(_X, tf_activation, sess=sess)

outputFeatureMapActivation(conv11)
Restore model/mine_3.ckpt
In [30]:
outputFeatureMapActivation(conv12)
Restore model/mine_3.ckpt
In [31]:
outputFeatureMapActivation(conv13)
Restore model/mine_3.ckpt
In [32]:
outputFeatureMapActivation(conv21)
Restore model/mine_3.ckpt

Question 9

Discuss how you used the visual output of your trained network's feature maps to show that it had learned to look for interesting characteristics in traffic sign images

Answer:

The origin image contain useless information in the background and we can still see it clearly in conv11 and conv12 layers. However, the following layers get rid of the redundant background information, and retain the edge information.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.